package com.situ.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;

public class UserServlet extends HttpServlet {
	
	private IUserService userService = new UserServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		String method = req.getParameter("method");
		switch (method) {
		case "login":
			login(req,resp);
			break;
		case "logOut":
			logOut(req,resp);
			break;
		default:
			break;
		}
	}

	private void logOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession();
		User user = (User)session.getAttribute("user");
		session.invalidate();
		resp.sendRedirect(req.getContextPath() + "/login.jsp");
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		String checkCode = req.getParameter("checkCode");
		String sessionCheckCode = (String)req.getSession().getAttribute("checkCode");
		if (null == checkCode
				||"".equals(checkCode)
				||checkCode.equalsIgnoreCase(sessionCheckCode) == false) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		System.out.println(name);
		System.out.println(password);
		User user = new User(name, password);
		HttpSession session = req.getSession();
		session.setAttribute("user", user);
		boolean result = false;
		result = userService.login(user);
		System.out.println(result);
		if (result) {
			resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
		} else {
			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
		}
	}
}
